/*
 * @lc app=leetcode.cn id=306 lang=cpp
 *
 * [306] 累加数
 */

// @lc code=start
class Solution {
public:
    string add(string num1, string num2){
        vector<int> A, B, C;
        for(int i = num1.size() - 1; i >= 0; i--) A.push_back(num1[i] - '0');
        for(int j = num2.size() - 1; j >= 0; j--) B.push_back(num2[j] - '0');
        for(int i = 0, t = 0; i < A.size() || i < B.size() || t; i++){
            if(i < A.size()) t += A[i];
            if(i < B.size()) t += B[i];
            C.push_back(t % 10);
            t /= 10;
        }
        string sum = "";
        for(int i = C.size() - 1; i >= 0; i--) sum += to_string(C[i]);
        return sum;
    }
    
    bool isAdditiveNumber(string num) {
        //[0, i]是第一个数  [a,b]
        //[i + 1, j]       [b+1,c]
        //枚举前两个数
        //O(N^3)
        for(int i = 0; i < num.size() ; i++)
            for(int j = i + 1; j + 1 < num.size(); j++){
                int a = 0, b = i, c = j;
                while(true){

                    //去除前导零
                    if(b - a + 1 > 1 && num[a] == '0' || c - b > 1 && num[b + 1] == '0') break;
                    string num1 = num.substr(a, b - a + 1);
                    string num2 = num.substr(b + 1, c - b);
                    string num3 = add(num1, num2);
                    
                    if(num.substr(c + 1, num3.size()) != num3) break;

                    a = b + 1;
                    b = c;
                    c = b + 1 + num3.size() - 1;

                    if(c == num.size() - 1) return true;
                }
            }
        return false;
    }
};
// @lc code=end

